import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { logout as logoutApi } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const isLogin = ref(!!token.value)

  // 计算属性
  const hasUserInfo = computed(() => {
    return Object.keys(userInfo.value).length > 0
  })

  // 方法
  function setToken(newToken) {
    token.value = newToken
    isLogin.value = true
    localStorage.setItem('token', newToken)
  }

  function setUserInfo(info) {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  async function logout() {
    try {
      // 调用后端退出登录API
      if (token.value) {
        await logoutApi()
      }
    } catch (error) {
      console.error('退出登录API调用失败:', error)
      // 即使API调用失败，也要清除本地数据
    } finally {
      // 清除本地状态
      token.value = ''
      userInfo.value = {}
      isLogin.value = false
      
      // 清除所有相关的本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 清除其他可能存在的用户相关数据
      localStorage.removeItem('cart')
      localStorage.removeItem('order')
      localStorage.removeItem('address')
      localStorage.removeItem('coupon')
      
      // 清除sessionStorage中的数据
      sessionStorage.clear()
      
      // 清除cookie（如果有的话）
      document.cookie.split(";").forEach(function(c) { 
        document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
      })
    }
  }

  function updateUserInfo(info) {
    userInfo.value = { ...userInfo.value, ...info }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  return {
    token,
    userInfo,
    isLogin,
    hasUserInfo,
    setToken,
    setUserInfo,
    logout,
    updateUserInfo
  }
}) 